import React, { createContext, useContext, useState, ReactNode } from "react";

interface CounterContextProps {
  counter: number;
  increment: () => void;
  decrement: () => void;
}

export const CounterContext = createContext<CounterContextProps | undefined>(
  undefined
);

interface CounterProviderProps {
  children: ReactNode;
}

const CounterProvider: React.FC<CounterProviderProps> = ({ children }) => {
  const [counter, setCounter] = useState(6);

  const increment = () => setCounter((prevCounter) => prevCounter + 1);
  const decrement = () => setCounter((prevCounter) => prevCounter - 1);

  return (
    <CounterContext.Provider value={{ counter, increment, decrement }}>
      {children}
    </CounterContext.Provider>
  );
};

export const ContextCounter: React.FC = () => {
  const { counter, increment, decrement } = useContext(CounterContext)!;

  return (
    <>
      <h1 data-testid="counter">{counter}</h1>
      <button data-testid="button-up" onClick={increment}>
        Up
      </button>
      <button data-testid="button-down" onClick={decrement}>
        Down
      </button>
    </>
  );
};

export default CounterProvider;
